/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.xspace.chatui.view.chat;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.util.EMLog;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.MediaBean;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;

import java.io.File;

import cn.xspace.chatui.R;
import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.util.OkHttpManager;
import okhttp3.Request;
import rx.functions.Action1;

/**
 * 语音row播放点击事件监听
 */
public class EaseChatRowVoicePlayClickListener implements View.OnClickListener {
    private static final String TAG = "VoicePlayClickListener";
    //	EMMessage message;
    private MsgRecordEntity message;
    //    EMVoiceMessageBody voiceBody;
    private ImageView voiceIconView;
    private TextView mTextview;
    private int timeLength = 0;
    private int timeCurent = 0;

    private AnimationDrawable voiceAnimation = null;
    MediaPlayer mediaPlayer = null;
    ImageView iv_read_status;
    Activity activity;
    Context mContext;
    private int chatType;
    private BaseAdapter adapter;
    private Handler mHandler = new Handler();
    public static boolean isPlaying = false;
    public static EaseChatRowVoicePlayClickListener currentPlayListener = null;
    public static String playMsgId;
    private static final int POLL_INTERVAL = 1000;

    public EaseChatRowVoicePlayClickListener(MsgRecordEntity message, ImageView v, ImageView iv_read_status, BaseAdapter adapter, Activity context) {
        this.message = message;
//        voiceBody = (EMVoiceMessageBody) message.getBody();
        this.iv_read_status = iv_read_status;
        this.adapter = adapter;
        voiceIconView = v;
        this.activity = context;
        this.chatType = message.msg_type;
    }

    public EaseChatRowVoicePlayClickListener(ImageView v, TextView timeTextView, Context context, int time) {
        voiceIconView = v;
        this.mContext = context;
        this.mTextview = timeTextView;
        this.timeLength = time;
        timeCurent = time;
    }

    /**
     * 判断是否是我发送的语音
     *
     * @return
     */
    private boolean isMySend() {
        if ("1".equals(message.is_mine)) {
            LogUtil.d(TAG, "isMySend  true");
            return true;
        } else {
            LogUtil.d(TAG, "isMySend  false");
            return false;
        }
    }

    private Runnable mPollTask = new Runnable() {
        public void run() {
//            double amp = mSensor.getAmplitude();
//            updateDisplay(amp);
            if (timeCurent != 0) {
                timeCurent -= 1;
            }
            mTextview.setText(timeCurent + "s");
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }
    };

    public void stopPlayVoice() {
        voiceAnimation.stop();
        if (!isMySend()) {
            voiceIconView.setImageResource(R.drawable.ease_chatfrom_voice_playing);
        } else {
            voiceIconView.setImageResource(R.drawable.ease_chatto_voice_playing);
        }

        // stop play voice
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        isPlaying = false;
        playMsgId = null;
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

    }

    public void stopQacVoice() {
        mHandler.removeCallbacks(mPollTask);
        mTextview.setText(timeLength + "s");
        voiceAnimation.stop();
        voiceIconView.setImageResource(R.drawable.icon_record_logo);
        // stop play voice
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        isPlaying = false;
        playMsgId = null;
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

    }

    public void playVoice(String filePath) {
        if (!(new File(filePath).exists())) {
            //文件不存在 ，再根据文件名字拼接路径判断是否存在
            return;
        }
        playMsgId = message.msg_id;
        AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

        mediaPlayer = new MediaPlayer();
//        if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setSpeakerphoneOn(true);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
//        } else {
//            audioManager.setSpeakerphoneOn(false);// 关闭扬声器
//            // 把声音设定成Earpiece（听筒）出来，设定为正在通话中
//            audioManager.setMode(AudioManager.MODE_IN_CALL);
//            mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
//        }
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mediaPlayer.release();
                    mediaPlayer = null;
                    stopPlayVoice(); // stop animation
                }

            });
            isPlaying = true;
            currentPlayListener = this;
            mediaPlayer.start();
            showAnimation();

            LogUtil.d(TAG, "visible ?" + (iv_read_status.getVisibility() == View.VISIBLE));
            // 如果是接收的消息
            if (!isMySend()) {
//                if (!message.isAcked() && chatType == ChatType.Chat) {
//                    // 告知对方已读这条消息
//                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
//                }
                if ((1 != message.mFileEntity.isMediaPlayed) && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
                    // 隐藏自己未播放这条语音消息的标志
                    iv_read_status.setVisibility(View.INVISIBLE);
                    message.mFileEntity.isMediaPlayed = 1;
//                    ChatFileDao.getInstance().updateFileIsPlayedFlag(message.inserttime, 1);

//                    ChatFileDao.getInstance().getiChatFileData().updateFileIsPlayedFlag(message.inserttime, 1)
//                            .subscribeOn(Schedulers.io())
//                            .observeOn(AndroidSchedulers.mainThread())
//                            .subscribe(commonAction);
//                    message.setListened(true);
//                    EMClient.getInstance().chatManager().setMessageListened(message);
                }
            }

        } catch (Exception e) {
            System.out.println();
        }
    }

    public void playQacVoice(String filePath) {
        if (!(new File(filePath).exists())) {
            //文件不存在 ，再根据文件名字拼接路径判断是否存在
            return;
        }
        playMsgId = filePath;
        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

        mediaPlayer = new MediaPlayer();
//        if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setSpeakerphoneOn(true);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
//        } else {
//            audioManager.setSpeakerphoneOn(false);// 关闭扬声器
//            // 把声音设定成Earpiece（听筒）出来，设定为正在通话中
//            audioManager.setMode(AudioManager.MODE_IN_CALL);
//            mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
//        }
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mediaPlayer.release();
                    mediaPlayer = null;
                    stopQacVoice(); // stop animation
                }

            });
            isPlaying = true;
            currentPlayListener = this;
            mediaPlayer.start();
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
            showQacAnimation();

        } catch (Exception e) {
            System.out.println();
        }
    }

    // show the voice playing animation
    private void showAnimation() {
        // play voice, and start animation
        if (!isMySend()) {
            voiceIconView.setImageResource(R.drawable.voice_from_icon);
        } else {
            voiceIconView.setImageResource(R.drawable.voice_to_icon);
        }
        voiceAnimation = (AnimationDrawable) voiceIconView.getDrawable();
        voiceAnimation.start();
    }

    private void showQacAnimation() {
        // play voice, and start animation
        voiceIconView.setImageResource(R.drawable.anima_voice_qac);
        voiceAnimation = (AnimationDrawable) voiceIconView.getDrawable();
        voiceAnimation.start();
    }

    public void qacVoicePlay(final MediaBean mediaBean) {
        LogUtil.d(TAG, "path " + mediaBean.content);
        String st = mContext.getResources().getString(R.string.Is_download_voice_click_later);
        if (isPlaying) {
            if (playMsgId != null && playMsgId.equals(mediaBean.content)) {
                currentPlayListener.stopQacVoice();
                return;
            }
            currentPlayListener.stopQacVoice();
        }
        if (TextUtils.isEmpty(mediaBean.content)) {
            //先判断，本地路径是否为空，如果为空，再将 名字拼接存放路径 判断是否存在
            mediaBean.content = AppConstant.FILE_ADDRESS + mediaBean.file_name;
        }

        if (!new File(mediaBean.content).exists()) {
            LogUtil.d(TAG,"wubaojie>>>qacVoicePlay: 文件不存在");
            T.showSingleL(st);
            //下载
            OkHttpManager.getInstance().downloadAsync(mediaBean.file_url, AppConstant.FILE_ADDRESS, mediaBean.file_name, new OkHttpManager.DataCallBack() {
                @Override
                public void requestBefore() {

                }

                @Override
                public void requestFailure(Request request, Exception e) {
//                imageView.setImageResource(R.drawable.chat_default_image_error);
                }

                @Override
                public void requestSuccess(BaseReturnBean result) throws Exception {
                }

                @Override
                public void requestSuccess(String result) throws Exception {
//                            imageView.setImageResource();
                    LogUtil.d(TAG, "本地下载路径为" + result);
                    mediaBean.content = result;
                    playQacVoice(result);
                }
            });
        } else {
            LogUtil.d(TAG,"wubaojie>>>qacVoicePlay: 文件存在，播放");
            playQacVoice(mediaBean.content);
        }

    }

    @Override
    public void onClick(View v) {
        LogUtil.d(TAG, "path " + message.mFileEntity.file_url_local);
        String st = activity.getResources().getString(R.string.Is_download_voice_click_later);
        if (isPlaying) {
            if (playMsgId != null && playMsgId.equals(message.msg_id)) {
                currentPlayListener.stopPlayVoice();
                return;
            }
            currentPlayListener.stopPlayVoice();
        }

        if (isMySend()) {
            if (TextUtils.isEmpty(message.mFileEntity.file_url_local)) {
                //先判断，本地路径是否为空，如果为空，再将 名字拼接存放路径 判断是否存在
                message.mFileEntity.file_url_local = AppConstant.VOICE_ADDRESS_DL + message.mFileEntity.file_name;
            }

            if (!new File(message.mFileEntity.file_url_local).exists()) {
                //再将远程路径的 文件名拼接路径 判断是否存在
                File remoteFile = new File(AppConstant.VOICE_ADDRESS_DL + AppConstant.getFileName(message.mFileEntity.file_url_remote));
                if (remoteFile.exists()) {
                    message.mFileEntity.file_url_local = AppConstant.VOICE_ADDRESS_DL + AppConstant.getFileName(message.mFileEntity.file_url_remote);
                    playVoice(message.mFileEntity.file_url_local);
                    return;
                }
                //重新下载
                Toast.makeText(activity, st, Toast.LENGTH_SHORT).show();
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
//                        EMClient.getInstance().chatManager().downloadAttachment(message);
                        getVoiceByHttp();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        super.onPostExecute(result);
                        adapter.notifyDataSetChanged();
                        playVoice(message.mFileEntity.file_url_local);
                    }

                }.execute();
                return;
            }
            // for sent msg, we will try to play the voice file directly
            playVoice(message.mFileEntity.file_url_local);
        } else {
            LogUtil.d(TAG, " file_download_status  " + message.mFileEntity.file_download_status);
            if (message.mFileEntity.file_download_status == ChatFileEntity.DownloadStatus.DOWNLOAD_COMPLETE.toNumber()) {
                File file = new File(message.mFileEntity.file_url_local);
                if (file.exists() && file.isFile())
                    playVoice(message.mFileEntity.file_url_local);
                else
                    EMLog.e(TAG, "file not exist");

            } else if (message.mFileEntity.file_download_status == ChatFileEntity.DownloadStatus.DOWNLOAD_ING.toNumber()) {
                Toast.makeText(activity, st, Toast.LENGTH_SHORT).show();
            } else if (message.mFileEntity.file_download_status == ChatFileEntity.DownloadStatus.DOWNLOAD_NOT.toNumber()) {
                Toast.makeText(activity, st, Toast.LENGTH_SHORT).show();
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
//                        EMClient.getInstance().chatManager().downloadAttachment(message);
                        getVoiceByHttp();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        super.onPostExecute(result);
                        adapter.notifyDataSetChanged();
                        playVoice(message.mFileEntity.file_url_local);
                    }
                }.execute();

            }

        }
    }

    private void getVoiceByHttp() {
        OkHttpManager.getInstance().downloadAsync(message.mFileEntity.file_url_remote, AppConstant.FILE_ADDRESS, message.mFileEntity.file_name, new OkHttpManager.DataCallBack() {
            @Override
            public void requestBefore() {
            }

            @Override
            public void requestFailure(Request request, Exception e) {
//                imageView.setImageResource(R.drawable.chat_default_image_error);
            }

            @Override
            public void requestSuccess(BaseReturnBean result) throws Exception {
            }

            @Override
            public void requestSuccess(String result) throws Exception {
//                            imageView.setImageResource();
                LogUtil.d(TAG, "本地下载路径为" + result);
                message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_COMPLETE.toNumber();
                //更新数据库状态

//                ChatFileDao.getInstance().updateFileDownLoadStausByTime(message.inserttime, ChatFileEntity.DownloadStatus.DOWNLOAD_COMPLETE.toNumber());
//                ChatFileDao.getInstance().getiChatFileData().updateFileDownLoadStausByTime(message.inserttime, ChatFileEntity.DownloadStatus.DOWNLOAD_FIALED.toNumber())
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(commonAction);
////                ChatFileDao.getInstance().updateFileLocalPath(message.inserttime, result);
//                ChatFileDao.getInstance().getiChatFileData().updateFileLocalPath(message.inserttime, result)
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(commonAction);
////                showImageView(result, imageView, message.mFileEntity.file_url_remote);
            }
        });
    }


    Action1 commonAction = new Action1() {
        @Override
        public void call(Object o) {

        }
    };
}
